package org.example.thymeleaf.demo.demos.controller;

import com.deepoove.poi.XWPFTemplate;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.*;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;


/**
 * @author wzx
 * @date 2024/9/9 17:39
 * @description: test
 */
@Controller("/")
public class TestController {

    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping("/showIndex")
    public String showIndex(Map<String, String> map) {
        map.put("msg","testMessage");
        return "index";
    }


    @GetMapping("/showEmp")
    public String showEmp(Model model) {
        model.addAttribute("showDiv", true);
        model.addAttribute("name", "哈喽单车");
        model.addAttribute("fileNo", "11111");
        model.addAttribute("time", "2024-09-09");
        model.addAttribute("text", "测试");
        model.addAttribute("fanan", "测试");
        model.addAttribute("zxTime", "2024-08-06");
        model.addAttribute("gsTime", "2024-08-06");
        model.addAttribute("xdTime", "2024-08-06");
        model.addAttribute("zx", "执行力");
        model.addAttribute("org", "开发部");
        model.addAttribute("sh", "总经理");
        model.addAttribute("pz", "审核通过");
        model.addAttribute("filePage", "10");
        return "showEmp";
    }


    // 下载文档
    @PostMapping("/genera")
    public void genera(@RequestBody Map<String, Object> requestData, HttpServletResponse response, Model model) throws Exception {
        // 从请求体中获取 contentRemoved 的状态
        Boolean showDiv = (Boolean) requestData.get("showDivValue");
        model.addAttribute("showDiv", showDiv);
        model.addAttribute("name", "哈喽单车");
        model.addAttribute("fileNo", "11111");
        model.addAttribute("time", "2024-09-09");
        model.addAttribute("text", "测试");
        model.addAttribute("fanan", "测试");
        model.addAttribute("zxTime", "2024-08-06");
        model.addAttribute("gsTime", "2024-08-06");
        model.addAttribute("xdTime", "2024-08-06");
        model.addAttribute("zx", "执行力");
        model.addAttribute("org", "开发部");
        model.addAttribute("sh", "总经理");
        model.addAttribute("pz", "审核通过");
        model.addAttribute("filePage", "10");


        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=\"generated-doc.docx\"");

        // 生成 Word 文件
        try (OutputStream os = response.getOutputStream()) {
            buildWord(model, os);
        } catch (Exception e) {
            e.printStackTrace();
            // 处理错误，例如返回500错误码
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Word文件出错");
        }
    }

    /**
     * 生成本地word
     * @param variables 模板需要的数据
     * @throws Exception
     */
    public  void buildWord( Model variables , OutputStream outputStream) throws Exception {

        // 配置模板引擎
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix("templates/");
        resolver.setSuffix(".html"); // 模板文件后缀

        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(resolver);

        // 构造上下文
        Context context = new Context();
        context.setVariables((Map<String, Object>) variables);

        // 使用 ByteArrayOutputStream 代替文件
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             PrintWriter writer = new PrintWriter(new OutputStreamWriter(byteArrayOutputStream, "UTF-8"))) {

            // 处理模板
            templateEngine.process("showEmp", context, writer);
            writer.flush();

            // 将内容写入到提供的输出流
            outputStream.write(byteArrayOutputStream.toByteArray());
        } catch (Exception e) {
            System.out.println("导出Word文件出错啦");
            e.printStackTrace();
            throw e;
        }
    }









}
